package com.xb.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xb.entity.*;
import com.xb.mapper.*;
import com.xb.service.IRegisterService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * Service业务层处理
 */
@Service
public class RegisterServiceImp implements IRegisterService {
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OutpatientQueueMapper outpatientQueueMapper;
    @Resource
    private PatientMapper patientMapper;
    @Resource
    private TollTakeDrugMapper tollTakeDrugMapper;
    @Resource
    private MedicalRecordMapper recordMapper;
    @Resource
    private MedicalExaminationMapper medicalExaminationMapper;


    /**
     * 分页查询列表
     *
     * @param register
     * @return
     */
    @Override
    public PageInfo<Register> selectRegisterList(Register register, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Register> list = registerMapper.selectAllRegisterList(register);
        return new PageInfo<Register>(list);
    }

    /**
     * 新增
     *
     * @param register
     * @return 结果
     */

    @Override
    @Transactional
    public Result insertRegister(Register register, HttpSession session) {
        Result result = new Result();
        try {
            if (registerMapper.selectRegister(register) != null) {
                result.setMessage("此用户已存在预约记录！");
                result.setStatus(Result.RESPONSE_FAIL);
                return result;
            }

            if (outpatientQueueMapper.selectOutpatientQueueByRegister(register) != null) {
                result.setMessage("此用户已存在预约记录！");
                result.setStatus(Result.RESPONSE_FAIL);
                return result;
            }

            if (tollTakeDrugMapper.selectTollTakeDrugByRegister(register) != null) {
                result.setMessage("此用户已存在预约记录！");
                result.setStatus(Result.RESPONSE_FAIL);
                return result;
            }
            if (recordMapper.selectMedicalRecordByRegister(register) != null) {
                result.setMessage("此用户已存在预约记录！");
                result.setStatus(Result.RESPONSE_FAIL);
                return result;
            }
            String email = (String) session.getAttribute("email");
            User createUser = userMapper.selectUserByEmail(email);
            User doctorInfo = userMapper.selectUserByUsername(register.getDoctor());
            if (doctorInfo.getAllowNum() >= doctorInfo.getNowNum() + 1) {
                doctorInfo.setNowNum(doctorInfo.getNowNum() + 1);
                userMapper.updateUser(doctorInfo);
            } else {
                result.setMessage("出错啦，预约满了");
                result.setStatus(Result.RESPONSE_FAIL);
                return result;
            }

            // 开始增加处方号！
            register.setRegisteredNum("RE" + System.currentTimeMillis());
            register.setCreateId(createUser.getId());
            register.setCreateName(createUser.getUsername());
            register.setDoctorId(doctorInfo.getId());
            register.setChargeStatus(0);
            if (register.getDepartmentId() == 11) {
                // 如果是体检就不执行增加处方号！使用刚刚待处理的处方号
                MedicalRecord medicalRecord = recordMapper.selectMedicalRecordById(register.getPatientId());
                MedicalExamination medicalExamination;
                if (medicalRecord != null) {
                    List<Register> registers = registerMapper.checkHaveAnAppointmentToday(register.getPatientId());
                    for (Register register1 : registers) {
                        Date appointmentDate = register1.getCreateDatetime(); // 替换为你的预约日期

                        // 获取今天的日期
                        LocalDate today = LocalDate.now();

                        // 将预约日期转换为LocalDate类型
                        LocalDate appointmentLocalDate = appointmentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        // 判断预约日期是否在今天
                        if (appointmentLocalDate.equals(today)) {
                            result.setMessage("该患者今天已预约过体检！");
                            result.setStatus(Result.RESPONSE_FAIL);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return result;
                        }

                    }
                    registerMapper.insertRegister(register);

                    medicalExamination = new MedicalExamination();
                    medicalExamination.setPrescriptionNum(medicalRecord.getPrescriptionNum());
                    medicalExamination.setRegisterId(register.getId());
                    medicalExaminationMapper.insertMedicalExamination(medicalExamination);
                } else {
                    throw new IllegalAccessException("请先咨询医生");
                }

                OutpatientQueue outpatientQueue = new OutpatientQueue();
                outpatientQueue.setRegisterId(register.getId());
                outpatientQueue.setUserId(doctorInfo.getId());
                outpatientQueue.setPatientId(register.getPatientId());
                Patient patient = patientMapper.checkPatient(register.getPatientId());
                outpatientQueue.setRemark(patient.getName() + "#" + register.getDoctor());
                outpatientQueueMapper.insertOutpatientQueue(outpatientQueue);
                result.setStatus(Result.RESPONSE_SUCCESS);
                return result;
            }

            registerMapper.insertRegister(register);

            OutpatientQueue outpatientQueue = new OutpatientQueue();
            outpatientQueue.setRegisterId(register.getId());
            outpatientQueue.setUserId(doctorInfo.getId());
            outpatientQueue.setPatientId(register.getPatientId());
            Patient patient = patientMapper.checkPatient(register.getPatientId());
            outpatientQueue.setRemark(patient.getName() + "#" + register.getDoctor());
            outpatientQueueMapper.insertOutpatientQueue(outpatientQueue);


            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            result.setMessage("请先咨询医生");
            result.setStatus(Result.RESPONSE_FAIL);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("预约失败！");
            result.setStatus(Result.RESPONSE_EXCEPTION);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

    }

    /**
     * 修改
     *
     * @param register
     * @return 结果
     */
    @Override
    public int updateRegister(Register register) {
        return registerMapper.updateRegister(register);
    }

}
